package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.to.WareSkuTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfoVo(SpuInfoVo spuInfoVo) {
        // 1. 保存SPU的基础信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo, spuInfoEntity);

        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        this.save(spuInfoEntity);

        // 2. 保存SPU的商品描述信息
        Long spuId = spuInfoEntity.getId();
        List<String> decripts = spuInfoVo.getDecript();

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        // spu_id不是自增主键，所以需要修改entity的@Table注解
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", decripts));

        spuInfoDescService.save(spuInfoDescEntity);

        // 3. 保存SPU的商品图片信息
        List<String> images = spuInfoVo.getImages();

        List<SpuImagesEntity> spuImagesEntities = images.stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();

            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setImgUrl(image);

            return spuImagesEntity;
        }).collect(Collectors.toList());

        spuImagesService.saveBatch(spuImagesEntities);

        // 4. 保存SPU的规格参数
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();

        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();

            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());

            AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());

            return productAttrValueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveBatch(productAttrValueEntities);

        // 5. 保存SPU积分信息
        Bounds bounds = spuInfoVo.getBounds();

        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);

        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if ((Integer) r.get("code") != 0) {
            log.error("添加积分信息失败");
        }

        // 6. 保存SKU信息
        List<Skus> skus = spuInfoVo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(sku -> {
                // 获取默认图片
                String defaultImage = "";
                List<Images> skuImages = sku.getImages();
                if (!CollectionUtils.isEmpty(skuImages)) {
                    for (Images img : skuImages) {
                        if (img.getDefaultImg() == 1) {
                            defaultImage = img.getImgUrl();
                        }
                    }
                }

                // 6.1 保存SKU基础信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);

                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setCatalogId(spuInfoVo.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoVo.getBrandId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoEntity.setSaleCount(0L);

                skuInfoService.save(skuInfoEntity);

                // 6.2 保存SKU图片
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = skuImages.stream().map(skuImage -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    BeanUtils.copyProperties(skuImage, skuImagesEntity);

                    skuImagesEntity.setSkuId(skuId);

                    return skuImagesEntity;
                }).filter(skuImage -> !StringUtils.isEmpty(skuImage.getImgUrl())).collect(Collectors.toList());

                skuImagesService.saveBatch(skuImagesEntities);

                // 6.3 保存SKU属性
                List<Attr> skuAttr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = skuAttr.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);

                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 6.4 保存减免信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);

                couponFeignService.saveSkuReduction(skuReductionTo);
            });
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 查询出spuId对应的sku商品
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        // TODO 这里是有BUG的，若在发布商品时选择了快速检索，并不会被发布的ES中
        // 获取可检索的属性
        List<ProductAttrValueEntity> productAttrValueEntityList = productAttrValueService.querySpuBaseAttr(spuId);
        List<Long> attrIds = productAttrValueEntityList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.queryAttrBySearch(attrIds);
        Set<Long> searchAttrIdSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> skuEsModelAttrs = productAttrValueEntityList
                .stream()
                .filter(productAttrValueEntity -> searchAttrIdSet.contains(productAttrValueEntity.getAttrId()))
                .map(productAttrValueEntity -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();

                    BeanUtils.copyProperties(productAttrValueEntity, attrs);
                    return attrs;
                }).collect(Collectors.toList());

        List<Long> skuIds = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // 获取sku信息
        R r = wareFeignService.hasStock(skuIds);
        Map<Long, Boolean> wareMap = null;
        try {
            List<WareSkuTo> wareSkuToList = r.getData(new TypeReference<List<WareSkuTo>>(){});
            wareMap = wareSkuToList.stream().collect(Collectors.toMap(WareSkuTo::getSkuId, WareSkuTo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常{}", e);
        }

        // 封装上架商品的检索信息
        Map<Long, Boolean> finalWareMap = wareMap;
        List<SkuEsModel> list = skuInfoEntityList.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);

            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            // 获取库存信息
            if (finalWareMap != null) {
                skuEsModel.setHasStock(finalWareMap.get(skuInfoEntity.getSkuId()));
            }
            //TODO 获取热度评分
            skuEsModel.setHotScore(0L);

            // 获取sku品牌信息
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            // 获取sku分类信息
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            // 添加属性检索条件
            skuEsModel.setAttrs(skuEsModelAttrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        R r1 = searchFeignService.upSpu(list);
        if (r1.getCode() == 0) {
            // 更新SPU上架状态
            baseMapper.updatePublishStatus(spuId, ProductConstant.PublishStatusEnum.UP_SPU.getCode());
        }
    }

}